package com.grao.waterschool.human.mngr;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.grao.waterschool.human.entiry.po.LogOperation;
import com.grao.waterschool.human.entiry.po.TSysTuser;
import com.grao.waterschool.human.manager.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {

    @Autowired
    private LogService logService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("----------------------------preHandle--------------------------");

        // 获取方法参数
        String params = JSONUtil.toJsonStr(request.getParameterMap());

        // 记录日志
        LogOperation logOperation = new LogOperation(getUsername(), request.getRequestURI(),
                request.getMethod(), params, request.getRemoteAddr());
        logService.logOperation(logOperation);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info("----------------------------afterCompletion--------------------------");

        if (ex != null) {
            // 记录异常日志
            LogOperation logOperation = new LogOperation(getUsername(), request.getRequestURI(),
                    request.getMethod(), JSONUtil.toJsonStr(request.getParameterMap()), ex.getClass().getName(), ex.getMessage(),
                    request.getRemoteAddr());
            logService.logOperation(logOperation);
        }
    }

    private String getUsername() {
        AtomicReference<String> name = new AtomicReference<>("匿名用户");
        if (StpUtil.isLogin()) {
            Optional.ofNullable(StpUtil.getSession().get("user"))
                    .ifPresent(u -> {
                        TSysTuser tuser = (TSysTuser) u;
                        name.set(tuser.getTnickname());
                    });
        }

        return name.get();
    }
}
